package com.test.www.Controller.admin;

import com.test.www.bean.BaseRes;
import com.test.www.bean.LoginRes;
import com.test.www.model.Users;
import com.test.www.service.UserService;
import com.test.www.utils.Constants;
import com.test.www.utils.json.JSONUtil;
import com.test.www.utils.log.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller //告诉编译器这里个控制器
//@RequestMapping("login")
public class LoginController {

    @Autowired  //这里使用@ualifier注解注入bookService业务层
    private UserService userService;

    //@RequestMapping("adminLogin")
    @ResponseBody
    @RequestMapping(value = "/adminLogin", method = RequestMethod.POST)
    public BaseRes adminLogin(@RequestBody LoginRes loginRes, HttpServletResponse response) { //@RequestParam("isbn")String isbn
        BaseRes res = new BaseRes();
        res.setCode(300);
        res.setMessage("登录失败");
        if (userService != null) {
            Users user = userService.login(loginRes.username1, loginRes.password1);
            if (user != null) {
                res.setCode(200);
                res.setMessage("登录成功");
                //存储到cookie
                Cookie cookie = new Cookie(Constants.USER_INFO_KEY, user.getuId()+"");    // (name,value);
                //注意：由于cookie的value值只能装字符串，所以我们将购物车对象（buycart）转化为json，再将json写入cookie的value值
                //关闭浏览器也要有Cookie，那就给它个生存时间就可以了
                cookie.setMaxAge(3600 * 24 * 7);
                //设置cookie路径
                cookie.setPath("/");
                //写入肯定是要用response
                response.addCookie(cookie);
            }
        }
        return res;
    }

    @RequestMapping("login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if (Constants.USER_INFO_KEY.equals(c.getName())) {
                    //拿到cookie名为Constants.BUYCART_COOKIE中的value
                    String value = c.getValue();
                    Users user = userService.selectByPrimaryKey( Integer.valueOf( value ) );
                    if (user != null) {
                        return "redirect:manage";
                    }
                    break;
                }
            }
        }
        return "admin/login.jsp";
    }

}
